package com.yanqu.manager;

import com.yanqu.CollectServer;
import com.yanqu.road.utils.MyProperties;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.time.Duration;
import java.util.Collections;

/**
 * 数数埋点的消费者
 */
public class LogKafkaConsumer {

    private String topic = "dzg_ta_log";

    private static final Logger logger = LogManager.getLogger(LogKafkaConsumer.class.getName());

    private KafkaConsumer<String, String> kafkaConsumer;

    private volatile boolean isStop = false;

    public LogKafkaConsumer() {

        String configPath = "";
        try{
            configPath = ResourceUtils.getFile("").getAbsolutePath() + File.separator+ "config" +File.separator;
        }catch (Exception e){
            logger.error("", e);
            throw new RuntimeException(e);
        }


        MyProperties myProperties = new MyProperties(configPath + "kafka.properties");

        if(!StringUtils.isNullOrEmpty(myProperties.getProperty("topic"))){
            this.topic = myProperties.getProperty("topic");
        }

        this.kafkaConsumer = new KafkaConsumer<>(myProperties.getProperties());


        new Thread(() -> {

            kafkaConsumer.subscribe(Collections.singleton(topic));

            while (!isStop){

                try {

                    ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(1000));
                    records.forEach(record -> {
                        CollectServer.getFileWrite().add(new StringBuilder().append(record.value()).append(System.lineSeparator()));
                    });

                }catch (Exception e){
                    logger.error("", e);
                }
            }

            kafkaConsumer.close();

            logger.info("kafkaConsumer close");

        }).start();

    }

    public void close(){
        isStop = true;
    }
}
